//
//  KZVocabularyImproveMakeTestVC.m
//  听说弱点强化训练
//
//  Created by 朱凯 on 2018/8/22.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "KZVocabularyImproveMakeTestVC.h"

// vc
#import "KZVocabularyImproveLookFailuresVC.h"
#import "KZUserMyNewWordVC.h"

// api
#import "KZVocabularyImproveNetApi.h"

// view
#import "KZVocabularyImproveTitleView.h"
#import "KZVocabularyImproveTestStatusView.h"
#import "KZLetterAnalysisView.h"
#import "KZVocabularyImproveTestResultView.h"
#import "KZAlertView.h"
#import "KZTimerView.h"

@interface KZVocabularyImproveMakeTestVC ()

@property (nonatomic, assign) NSInteger index;      // 当前词汇在包中索引
@property (nonatomic, strong) KZVocabularyImproveTitleView *titleView;
@property (nonatomic, strong) KZTimerView *timeView;

@property (nonatomic, strong) KZVocabularyImproveTestStatusView *testView;
@property (nonatomic, strong) KZVocabularyImproveTestResultView *resultView;

@end

@implementation KZVocabularyImproveMakeTestVC

- (void)dealloc {
    
    NSLog(@"vc销毁了");
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNaviUI];
    [self setupUI];
    
    // 记录当前题目的索引
    self.index = _packageModel.currentPackage.ReviewVocabularyNum.integerValue;
    
    // 从包的第一题开始做，则不需要弹框，否则弹框提示当前为第几题
    if (_index == 0) {
        // TODO: 等接口
        [self beginTest];
    } else {
        [self welcomeBack];
    }
}
#pragma mark - 创建视图
- (void)setupNaviUI {
    
    self.title = _type == KZVocabularyTypeLS ? @"听说词汇强化学习" : @"生词听说强化学习";
    [self addLeftBackBarButtonItem];
    
    // 定时器视图
    _timeView = [[KZTimerView alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
    __weak typeof(self) wself = self;
    _timeView.clickBlock = ^(BOOL isPause) {
        // 内部点击暂停要暂停资源，并弹出“休息”视图
        if (isPause) {
            [wself.testView pauseSource];
            [wself rest];
        }
    };
    [self addCustomItemviews:@[_timeView] position:ByNavigationItemPositionModeRight];

}
- (void)setupUI {
    
    _titleView = [KZVocabularyImproveTitleView new];
    _titleView.packageModel = _packageModel;
    [self.view addSubview:_titleView];
    [_titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(@0);
        make.height.equalTo(@40);
    }];
}
- (void)setupTestView {
    
    _testView = [KZVocabularyImproveTestStatusView new];
    _testView.packageModel = _packageModel;
    _testView.model = _packageModel.currentPackage.Detail[_index];
    [self.view addSubview:_testView];
    [_testView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(@0);
        if (@available(ios 11.0,*)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.equalTo(@0);
        }
    }];
    __weak typeof(self) wself = self;
    _testView.nextBlock = ^ {
        [wself next];
    };
    _testView.successStayBlock = ^{
        __strong typeof(self) sself = wself;
        [sself savaCurrentVocabularyData];
        sself->_index ++;
    };
    _testView.failureStayBlock = ^{
        __strong typeof(self) sself = wself;
        [sself savaCurrentVocabularyData];
        sself->_index ++;
    };
    
}
- (void)setupResultView {
    
    _resultView = [[KZVocabularyImproveTestResultView alloc] initWithReviewType:0];
    _resultView.packageModel = _packageModel;
    [self.view addSubview:_resultView];
    [_resultView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(@0);
        if (@available(ios 11.0,*)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.equalTo(@0);
        }
    }];
    __weak typeof(self) wself = self;
    _resultView.clickBlock = ^(int func) {
        switch (func) {
            case 0:
                // 下个包
                [wself nextPackage];
                break;
            case 1:
                // 查看不合格自会
                [wself browseFailureLetters];
                break;
            case 2:
                // 关闭窗口
                [wself closeWindow];
                break;
            case 3:
                // 去我的生词本
                [wself gotoMyUnfamiliarsBook];
                break;
            default:
                break;
        }
    };
}

#pragma mark - Net，听说词汇和生词接口几乎一样，首次进入不会调用查询接口，只有点击下个包才会调用
#pragma mark ------- 听说词汇
// 获取听说词汇包信息
- (void)getListenSayVocabularyPackageInfo {
    
    [MBProgressHUD showLoadind:@"正在查询待下一个听说词汇包，请稍候..."];
    
    KZVocabularyImproveNetApi *api = [KZVocabularyImproveNetApi new];
    api.requestParam = @{@"stageNo":KGetUserDefaults(@"TestLayer"),
                         @"schoolId":DR_UserInfo.SchoolID,
                         @"stuId":DR_UserInfo.UserID,};
    [api getListenSayVocabularyPackageInfo:^(KZVocabularyPackageModel *model) {
        
        [MBProgressHUD hideHud];
        
        // 全局model更换
        _packageModel = model;
        
        // 顶部标题信息更换
        _titleView.packageModel = _packageModel;
        
        // 重新开始计时
        [_timeView start];
        
        // 隐藏结果视图，并重新创建做题视图
        [UIView animateWithDuration:1 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:0 options:0 animations:^{
            _resultView.transform = CGAffineTransformMakeTranslation(0, _resultView.height);
        } completion:^(BOOL finished) {
            
            [_resultView removeFromSuperview];
            
            [self setupTestView];
            [self.view layoutIfNeeded];
            _testView.transform = CGAffineTransformMakeTranslation(-_testView.width, 0);
            [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:0 options:0 animations:^{
                _testView.transform = CGAffineTransformIdentity;
            } completion:^(BOOL finished) {
            }];
        }];
        
    } failuer:^(NSString *error) {
        [MBProgressHUD showFailureWithText:error];
    }];
}
// 保存记录：退出时或进入下一包时
- (void)saveListenSayVocabularyTrainRecord {
    
    KZVocabularyImproveNetApi *api = [KZVocabularyImproveNetApi new];
    NSMutableArray *temp = [NSMutableArray new];
    
    
    // 当前做完的最后一题的索引传递更新，上传做题时间
    _packageModel.currentPackage.UsedTime = @(_timeView.time);
    _packageModel.currentPackage.ReviewVocabularyNum = [NSString stringWithFormat:@"%li", _index + 1];
    // 设置是否完成
    _packageModel.currentPackage.IsComplete = [NSString stringWithFormat:@"%i", _index + 1 == _packageModel.currentPackage.Detail.count];
    [temp addObject:[_packageModel.currentPackage.Detail[_index] yy_modelToJSONObject]];
    
//    for (int i = 0; i < _index; i ++) {
//        KZVocabularyCurrentPackageDetailModel *detailModel = _packageModel.currentPackage.Detail[i];
//        NSDictionary *modelDic = [detailModel yy_modelToJSONObject];
//        [temp addObject:modelDic];
//    }
    
    NSMutableDictionary *dic = [_packageModel.currentPackage yy_modelToJSONObject];
    dic[@"Detail"] = temp.copy;
    
    api.requestParam = @{@"stageNo":KGetUserDefaults(@"TestLayer"),
                         @"schoolId":DR_UserInfo.SchoolID,
                         @"stuId":DR_UserInfo.UserID,
                         @"ModelListenSayVocabularyPackage": dic
                         };
    NSLog(@"kzkz: %@", api.requestParam.yy_modelToJSONString);
    [api saveListenSayVocabularyTrainRecord:^{

    } failuer:^(NSString *error) {
    }];
}
#pragma mark ------- 生词
// 获取听说词汇包信息
- (void)getUnfamiliarVocabularyPackage {
    
    [MBProgressHUD showLoadind:@"正在查询待下一生词包，请稍候..."];
    
    KZVocabularyImproveNetApi *api = [KZVocabularyImproveNetApi new];
    api.requestParam = @{@"stageNo":KGetUserDefaults(@"TestLayer"),
                         @"schoolId":DR_UserInfo.SchoolID,
                         @"stuId":DR_UserInfo.UserID,};
    [api getUnfamiliarVocabularyPackage:^(KZVocabularyPackageModel *model) {
        
        [MBProgressHUD hideHud];
        
        _packageModel = model;
        _titleView.packageModel = _packageModel;
        
        // 开始计时
        [_timeView start];
        
        // 隐藏结果视图
        [UIView animateWithDuration:1 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:0 options:0 animations:^{
            _resultView.transform = CGAffineTransformMakeTranslation(0, _resultView.height);
        } completion:^(BOOL finished) {
            
            [_resultView removeFromSuperview];
            
            [self setupTestView];
            [self.view layoutIfNeeded];
            _testView.transform = CGAffineTransformMakeTranslation(-_testView.width, 0);
            [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:0 options:0 animations:^{
                _testView.transform = CGAffineTransformIdentity;
            } completion:^(BOOL finished) {
            }];
        }];
        
    } failuer:^(NSString *error) {
        
        [MBProgressHUD showFailureWithText:error];
    }];
}
// 保存记录
- (void)saveUnfamiliarVocabularyTrainRecord {
    
    KZVocabularyImproveNetApi *api = [KZVocabularyImproveNetApi new];
    NSMutableArray *temp = [NSMutableArray new];
    
    _packageModel.currentPackage.UsedTime = @(_timeView.time);
    _packageModel.currentPackage.ReviewVocabularyNum = [NSString stringWithFormat:@"%li", _index + 1];
    // 设置是否完成
    NSLog(@"kz_index: %li", _index);
    // 在_index==19时候，应该已经做完了整个包
    _packageModel.currentPackage.IsComplete = [NSString stringWithFormat:@"%i", _index + 1 == _packageModel.currentPackage.Detail.count];
    [temp addObject:[_packageModel.currentPackage.Detail[_index] yy_modelToJSONObject]];
//    for (int i = 0; i < _index; i ++) {
//        KZVocabularyCurrentPackageDetailModel *detailModel = _packageModel.currentPackage.Detail[i];
//        NSDictionary *modelDic = [detailModel yy_modelToJSONObject];
//        [temp addObject:modelDic];
//    }
    
    NSMutableDictionary *dic = [_packageModel.currentPackage yy_modelToJSONObject];
    dic[@"Detail"] = temp.copy;
    
    api.requestParam = @{@"stageNo":KGetUserDefaults(@"TestLayer"),
                         @"schoolId":DR_UserInfo.SchoolID,
                         @"stuId":DR_UserInfo.UserID,
                         @"ModelUnfamiliarVocabularyPackage": dic
                         };
    
    NSLog(@"kz:%@", [api.requestParam yy_modelToJSONString]);
    [api saveUnfamiliarVocabularyTrainRecord:^{

    } failuer:^(NSString *error) {
    }];
}

#pragma mark - 事件
// 开始测试
- (void)beginTest {
    
    _timeView.time = _packageModel.currentPackage.UsedTime.integerValue;
    [self setupTestView];
}
// 如果之前某个包没做完，则继续做该包
- (void)welcomeBack {
    
    NSString *text;
    NSString *subText;
    if (_type == KZVocabularyTypeLS) {
        text = [NSString stringWithFormat:@"欢迎回来~\n据小鸽记录，您将继续第%li个词汇的训练", _index + 1];
        subText = [NSString stringWithFormat:@"第%li个词汇", _index + 1];
    } else {
        text = [NSString stringWithFormat:@"欢迎回来~\n据小鸽记录，您将继续第%li个词汇的训练", _index + 1];
        subText = [NSString stringWithFormat:@"第%li个词汇", _index + 1];
    }
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:text];
    [attrStr addAttribute:NSForegroundColorAttributeName value:UIColor.orangeColor range:[text rangeOfString:subText]];
    
    // 跳了很多级时有可能出现在上一级那里(bug)
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        KZAlertView *alert = [KZAlertView new];
        [alert showWithTitle:@"温馨提示" subtitle:attrStr.copy submitTypes:@[@0] submitButtonsConfig:^(NSArray<UIButton *> *buttons) {
            
            [buttons.firstObject setTitle:@"继续训练" forState:UIControlStateNormal];
        } click:^(NSInteger index) {
            
            [self beginTest];
            
        } destroyAtClickIndex:@[@0]];
    });
    
}
// 休息
- (void)rest {
    
    // 弹框提示
    NSMutableAttributedString *subtitle = [[NSMutableAttributedString alloc] initWithString:@"劳逸结合能提高训练效率\n持之以恒能提升训练效果\n\n\t我等你回来哟~\n\n\t\t\t-----蓝小鸽"];
    if (_testView.isPauseAtRecording) {
//        subtitle = [[NSMutableAttributedString alloc] initWithString:@"劳逸结合能提高训练效率\n持之以恒能提升训练效果\n\n\t我等你回来哟~\n\n\t\t\t-----蓝小鸽\n\n您在录音中暂停作答，恢复作答时将重新录音!!请准备!"];
//        [subtitle addAttribute:NSForegroundColorAttributeName value:UIColor.redColor range:[subtitle.string rangeOfString:@"您在录音中暂停作答，恢复作答时将重新录音!!请准备!"]];
         subtitle = [[NSMutableAttributedString alloc] initWithString:@"哎呀，正在录音被你打断了，一会儿得重新开始了呦"];
    }
    KZAlertView *alert = [KZAlertView new];
    [alert showWithTitle:@"温馨提示" subtitle:subtitle submitTypes:@[@0] submitButtonsConfig:^(NSArray<UIButton *> *buttons) {
        
        [buttons.firstObject setTitle:@"继续训练" forState:UIControlStateNormal];
    } click:^(NSInteger index) {
        
        // 恢复定时器，恢复资源
        [_timeView resume];
        [_testView beginSource];
        
    } destroyAtClickIndex:@[@0]];
}
// 返回按钮点击
- (void)leftItemsAction:(NSInteger)leftIndex {
    
    // 已经做完了这个包，返回就不用弹框了
    if (_index == _packageModel.currentPackage.Detail.count) {
        [self closeWindow];
        return;
    }
    
    // 点击返回按钮，先暂停当前训练和定时器
    [_testView pauseSource];
    [_timeView pause];
    
    NSMutableAttributedString *subtitle = [[NSMutableAttributedString alloc] initWithString:@"你确定要退出\n听说词汇强化训练吗？"];
    if (_testView.isPauseAtRecording) {
//        subtitle = [[NSMutableAttributedString alloc] initWithString:@"你确定要退出\n听说词汇强化训练吗？\n\n您在录音中暂停作答，恢复作答时将重新录音!!请准备!"];
//        [subtitle addAttribute:NSForegroundColorAttributeName value:UIColor.redColor range:[subtitle.string rangeOfString:@"您在录音中暂停作答，恢复作答时将重新录音!!请准备!"]];
         subtitle = [[NSMutableAttributedString alloc] initWithString:@"哎呀，正在录音被你打断了，一会儿得重新开始了呦"];
    }
    
    // 弹框提示
    KZAlertView *alert = [KZAlertView new];
    [alert showWithTitle:@"温馨提示" subtitle:subtitle submitTypes:@[@0, @1] submitButtonsConfig:^(NSArray<UIButton *> *buttons) {
        
        [buttons.firstObject setTitle:@"退出训练" forState:UIControlStateNormal];
        [buttons.lastObject setTitle:@"继续训练" forState:UIControlStateNormal];
    } click:^(NSInteger index) {
        // 点击退出
        if (index == 0) {
            
            [self closeWindow];
        }
        // 点击继续
        else {
            // 开启资源
            [_testView beginSource];
            [_timeView resume];
        }
        
    } destroyAtClickIndex:@[@0, @1]];
}
// 下一个词汇
- (void)next {
    
    [UIView animateWithDuration:1 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:0 options:0 animations:^{
        _testView.transform = CGAffineTransformMakeTranslation(0, _testView.height);
    } completion:^(BOOL finished) {
        [_testView removeFromSuperview];
        
        // 训练完成
        if (_index >= _packageModel.currentPackage.Detail.count) {
            NSLog(@"已完成本包的词汇学习，进入下一学习");
            [self onePackageTrainOver];
            return;
        }
        
        // 改变左上角索引
        _titleView.currentIndex = _index;
        // 开启下一个测试
        [self setupTestView];
        [self.view layoutIfNeeded];
        _testView.transform = CGAffineTransformMakeTranslation(_testView.width, 0);
        [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:0 options:0 animations:^{
            _testView.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
        }];
    }];
}
// 本包词汇学习完成，显示结果视图
- (void)onePackageTrainOver {
    
    // 关闭顶部计时器
    [_timeView stop];
    
    // 做完保存数据
//    [self saveData:true];
    
    [self setupResultView];
    [self.view layoutIfNeeded];
    
    _resultView.transform = CGAffineTransformMakeScale(0.01, 0.01);
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:0 options:0 animations:^{
        _resultView.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        [_testView removeFromSuperview];
    }];
}

// 查看不合格词汇
- (void)browseFailureLetters {
    
    NSMutableArray *temp = [NSMutableArray new];
    for (int i = 0; i < _packageModel.currentPackage.Detail.count; i ++) {
        KZVocabularyCurrentPackageDetailModel *model = _packageModel.currentPackage.Detail[i];
        if (!model.IsPassed.boolValue) {
            [temp addObject:model];
        }
    }
    KZVocabularyImproveLookFailuresVC *vc = [KZVocabularyImproveLookFailuresVC new];
    vc.failureModels = temp.copy;
    [self push:vc];
}
// 关闭窗口
- (void)closeWindow {
    
    // 销毁资源
    [_testView freeSource];
    // 关闭顶部定时器
    [_timeView stop];
    // 返回
    [self dismissViewControllerAnimated:true completion:nil];
    // 如果已经做完了，则不需要提交了，之前已经保存过了
//    if (_index == _packageModel.currentPackage.Detail.count) {
////        [self saveData:true];
//    } else {
//        [self saveData:false];
//    }
}
// 保存数据：是否完成
- (void)savaCurrentVocabularyData {
    if (_type == KZVocabularyTypeLS) {
        [self saveListenSayVocabularyTrainRecord];
    } else {
        [self saveUnfamiliarVocabularyTrainRecord];
    }
}
// 去我的生词本
- (void)gotoMyUnfamiliarsBook {
    
    [MBProgressHUD showOnlyText:@"去我的生词本"];
    KZUserMyNewWordVC *vc = [KZUserMyNewWordVC new];
    [self push:vc];
}
// 下个词汇包
- (void)nextPackage {
    
    // 保存本包内容，并请求下一个包的内容
    if (_type == KZVocabularyTypeLS) {
        self.index = 0;
        [self getListenSayVocabularyPackageInfo];
    } else {
        self.index = 0;
        [self getUnfamiliarVocabularyPackage];
    }
    
}

#pragma mark - setter
// 设置当前索引，修改titleView的索引
- (void)setIndex:(NSInteger)index {
    _index = index;
    _titleView.currentIndex = index;
}

@end
